package com.hhq.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhq.system.converter.TenantConverter;
import com.hhq.system.mapper.SysTenantMapper;
import com.hhq.system.mapper.SysUserTenantMapper;
import com.hhq.system.model.entity.SysTenant;
import com.hhq.system.model.entity.SysUserTenant;
import com.hhq.system.model.vo.TenantVO;
import com.hhq.system.security.util.SecurityUtils;
import com.hhq.system.service.SysUserTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/28 10:17
 */
@Service
public class SysUserTenantServiceImpl extends ServiceImpl<SysUserTenantMapper, SysUserTenant> implements SysUserTenantService {

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Autowired
    private TenantConverter tenantConverter;

    @Override
    public List<TenantVO> getTenants() {
        LambdaQueryWrapper<SysTenant> tenantLambdaQueryWrapper = Wrappers.lambdaQuery(SysTenant.class);
        if (SecurityUtils.isRoot()) {
            return tenantConverter.convertToVo(sysTenantMapper.selectList(tenantLambdaQueryWrapper));
        } else {
            Long userId = SecurityUtils.getUserId();
            LambdaQueryWrapper<SysUserTenant> queryWrapper = Wrappers.lambdaQuery(SysUserTenant.class);
            queryWrapper.eq(SysUserTenant::getUserId, userId);
            List<Long> tenantIds = baseMapper.selectList(queryWrapper).stream().map(SysUserTenant::getTenantId).collect(Collectors.toList());

            if (CollectionUtil.isEmpty(tenantIds)) {
                return new ArrayList<>();
            }
            tenantLambdaQueryWrapper.in(SysTenant::getId, tenantIds).orderByDesc(SysTenant::getCreateTime);
            List<SysTenant> sysTenants = sysTenantMapper.selectList(tenantLambdaQueryWrapper);
            return tenantConverter.convertToVo(sysTenants);
        }
    }
}
